const faker = require('faker');
// createTable.js
const pool = require('./index.js');
const createUserTable = () => {
    console.log('pool--', pool);

    const sql = `
        CREATE TABLE IF NOT EXISTS users (
            id INT AUTO_INCREMENT PRIMARY KEY,
            name VARCHAR(50) NOT NULL UNIQUE,
            password VARCHAR(255) NOT NULL,
            email VARCHAR(100) NOT NULL UNIQUE,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )
    `;

    pool.query(sql, (err, results) => {
        if (err) {
            console.error('Error creating table: ', err);
            return;
        }
        console.log('Users table created or already exists');
    });
};




const createBookTable = () => {
    console.log('pool--', pool);

    const sql = `
        CREATE TABLE IF NOT EXISTS books (
            id INT AUTO_INCREMENT PRIMARY KEY,
            name VARCHAR(50) NOT NULL UNIQUE,
            des VARCHAR(255) NOT NULL,
            type VARCHAR(100) NOT NULL UNIQUE,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )
    `;

    pool.query(sql, (err, results) => {
        if (err) {
            console.error('Error creating table: ', err);
            return;
        }
        console.log('books table created or already exists');
    });
};





// 生成随机字符串
function getRandomString(length) {
    const characters = '中文书名书名书名书名书名';
    let result = '';
    for (let i = 0; i < length; i++) {
        const randomIndex = Math.floor(Math.random() * characters.length);
        result += characters[randomIndex];
    }
    return result;
}

const axios = require('axios');

async function generateChineseText(prompt) {
    const response = await axios.post('https://api.openai.com/v1/engines/text-davinci-003/completions', {
        prompt: prompt,
        max_tokens: 100, // 调整生成的长度
        temperature: 0.7, // 控制随机性
        n: 1,
        stop: null,
    }, {
        headers: {
            'Authorization': `Bearer YOUR_API_KEY`,
            'Content-Type': 'application/json',
        }
    });

    return response.data.choices[0].text.trim();
}





// // 插入数据到 books 表
// const insertBooks = async () => {
//     await new Promise((resolve, reject) => {
//         const deleteQuery = 'DELETE FROM books WHERE id <= 1000'; // 根据你的 id 来决定删除哪些记录
//         pool.query(deleteQuery, (error, results) => {
//             if (error) {
//                 return reject(error);
//             }
//             console.log('Deleted existing books.');
//             resolve(results);
//         });
//     });
//     // for (let i = 0; i < 100; i++) {
//     //     const name = getRandomString(10); // 随机书名
//     //     const des = getRandomString(50); // 随机描述
//     //     const type = getRandomString(5); // 随机类型
//     //     const createdAt = new Date().toISOString().slice(0, 19).replace('T', ' '); // 当前时间

//     //     const query = 'INSERT INTO books (name, des, type, created_at) VALUES (?, ?, ?, ?)';
//     //     const values = [name, des, type, createdAt];

//     //     // 使用 Promise 包装查询
//     //     await new Promise((resolve, reject) => {
//     //         pool.query(query, values, (error, results) => {
//     //             if (error) {
//     //                 return reject(error);
//     //             }
//     //             console.log(`Inserted book ${i + 1}: ${name}`);
//     //             resolve(results);
//     //         });
//     //     });
//     // }


// };











// 生成随机数据并插入数据库
const insertBooks = async () => {
    const insertQuery = 'INSERT INTO books (name, des, type) VALUES (?, ?, ?)';
    const types = ['小说', '科幻', '历史', '哲学', '教育', '技术'];

    // 使用 Promise.all 进行批量插入
    const promises = Array.from({ length: 100 }).map(() => {
        const name = faker.name.findName(); // 生成随机中文名
        const des = faker.lorem.sentence(); // 生成随机描述
        const bookType = types[Math.floor(Math.random() * types.length)]; // 随机选择类型
        
        return new Promise((resolve, reject) => {
            pool.query(insertQuery, [name, des, bookType], (error, results) => {
                if (error) {
                    return reject(error);
                }
                resolve(results);
            });
        });
    });

    try {
        await Promise.all(promises);
        console.log('成功插入 100 条数据到 books 表。');
    } catch (error) {
        console.error('插入数据时出错:', error);
    } finally {
        // connection.end();
    }
};

// 执行函数
insertBooks();
